package com.bruan.threadsafe_lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Account {
    private String cardId;
    private double money;

    //创建一个锁对象,每个实例都有lk
    private final Lock lk = new ReentrantLock();

    public Account() {
    }

    public Account(String cardId, double money) {
        this.cardId = cardId;
        this.money = money;
    }

    public String getCardId() {
        return cardId;
    }

    public void setCardId(String cardId) {
        this.cardId = cardId;
    }

    public double getMoney() {
        return money;
    }

    public void setMoney(double money) {
        this.money = money;
    }

    public void drawMoney(double money) {
        //搞清楚谁取钱
        String name = Thread.currentThread().getName();
        try {
            lk.lock();
            if (this.money>=money){
                System.out.println(name+"取钱"+money+"成功！");
                this.money-=money;
                System.out.println(name+"余额剩余："+this.money);
            }else {
                System.out.println(name+"余额不足");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            //一定要解锁
            lk.unlock();
        }
    }
}
